﻿using System;
using System.Collections.Generic;
using System.Linq;

using mvcForum.Core.Abstractions.Interfaces;

namespace mvcForum.Web.Cache {

	public class PerRequestCache : IPerRequestCache {
		private Dictionary<String, TypeCache<ICacheable>> cache = new Dictionary<String, TypeCache<ICacheable>>();
		private Dictionary<String, object> untypedCache = new Dictionary<string, object>();

		public T Pull<T>(int id) where T : ICacheable {
			string typeName = typeof(T).Name;
			if (this.cache.ContainsKey(typeName)) {
				if (this.cache[typeName].Elements.ContainsKey(id)) {
					return (T)this.cache[typeName].Elements[id];
				}
			}
			return default(T);
		}

		public void Push<T>(T element) where T : ICacheable {
			string typeName = typeof(T).Name;
			if (!cache.ContainsKey(typeName)) {
				cache.Add(typeName, new TypeCache<ICacheable>());
			}
			if (cache[typeName].Elements.Where(x => x.Key == element.Id).Any()) {
				cache[typeName].Elements[element.Id] = element;
			}
			else {
				cache[typeName].Elements.Add(element.Id, element);
			}
		}

		public object Pull(String key) {
			if (untypedCache.ContainsKey(key)) {
				return untypedCache[key];
			}
			return null;
		}

		public void Push(String key, object value) {
			if (untypedCache.ContainsKey(key)) {
				untypedCache[key] = value;
			}
			else {
				untypedCache.Add(key, value);
			}
		}
	}
}